<script setup lang="ts">
//生命周期函数
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import {
  reqRoleAuthUserAllocatedListUrL,
  reqRoleAuthUserCancelAllUrl,
  reqRoleAuthUserCancelUrl
} from "@/api/system/role";
import SelectUser from "./selectUser.vue";
import { useTagsViewStore } from "@/store/modules/tagsView";

const $route = useRoute(); /*获取当前路由对象*/
const $router = useRouter();
const TabsStore = useTagsViewStore();
const userIds = ref([]);
const { proxy }: any = getCurrentInstance();

onMounted(() => {
  //获取第一页的信息
  const roleId = $route.params && $route.params.roleId;
  console.log(roleId);
  /*根据roleId来获取当前角色所分配的用户信息*/
  /*将所有的用户信息分页展示出来*/
  if (roleId) {
    queryParams.roleId = roleId;
    handleQuery();
  }
});

//////////////////////////////////////////
/*查询*/
const queryForm = ref<FormInstance>();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 2,
  roleId: "",
  username: "" /*用户名*/,
  phonenumber: "" /*手机号*/
});
const total = ref(0); /*总计*/
const loading = ref(true); /*遮罩层*/
const showSearch = ref(true); /*是否显示搜索*/
const userList = ref();
const select = ref();
const multiple = ref(true);
/*查询*/
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/*获取数据*/
const getList = async () => {
  loading.value = true;
  await reqRoleAuthUserAllocatedListUrL(queryParams)
    .then((response) => {
      userList.value = response.rows;
      total.value = response.total;
      console.log(response);
      //将查询结果展示出来
      loading.value = false;
    })
    .catch((e) => {
      ElMessage.error(e);
    });
};
/*重置查询表单*/
const resetQuery = () => {
  proxy.$resetForm(queryForm);
};

/*打开添加用户*/
const openSelectUser = () => {
  select.value.initFormData();
};
/*批量取消授权*/
const cancelAuthUserAll = async () => {
  const roleId = queryParams.roleId;
  const user_Ids = userIds.value.join(",");
  /*如果没有选中*/
  if (user_Ids == "" || user_Ids == null) {
    proxy.$modal.msgWarning("请选择要取消角色权限的用户！");
    return;
  }
  await reqRoleAuthUserCancelAllUrl({ userIds: user_Ids, roleId: roleId })
    .then((req) => {
      if (req.code === 200) {
        proxy.$modal.msgSuccess(req.message != null ? req.message : "取消授权成功");
      } else {
        proxy.$modal.msgError("取消授权失败！");
        return;
      }
    })
    .catch((e) => {
      console.log(e);
      proxy.$modal.msgError(e.message);
      return;
    });
  /*再次查询*/
  await getList();
};

/*取消授权*/
const cancelAuthUser = async (row: any) => {
  const userRole = {
    roleId: queryParams.roleId,
    userId: row.userId
  };
  await reqRoleAuthUserCancelUrl(userRole)
    .then((req: any) => {
      if (req.code === 200) {
        proxy.$modal.msgSuccess("取消授权成功");
      } else {
        proxy.$modal.msgError("取消授权失败！");
        return;
      }
    })
    .catch((e: any) => {
      console.log(e);
      proxy.$modal.msgError(e.message);
      return;
    });
  /*再次查询*/
  await getList();
};

/*关闭该角色分配界面*/
const handleClose = () => {
  // 返回按钮
  const obj = { path: $route.path };
  TabsStore.delView(obj).then((editableTabs: any) => {
    /*如果要删除的界面是活动界面*/
    console.log(editableTabs);
    if (isActive(obj)) {
      toLastView(editableTabs, obj);
    }
  });
};

/*路由到相应界面*/
const toLastView = (editableTabs: any, view: any) => {
  const lastView = editableTabs.slice(-1)[0];
  if (lastView) {
    console.log(lastView);
    TabsStore.activeTabsValue = lastView.fullPath;
    $router.push(lastView.fullPath || lastView.path);
  } else {
  }
};

/*多选框选中数据*/
const handleSelectionChange = (selection: any) => {
  userIds.value = selection.map((item: any) => item.userId); /*将多选框选中后的数据放到userIds中*/
  multiple.value = !selection.length;
};

/*判断是否是激活状态*/
const isActive = (tag: any) => {
  return $route.path === tag.path;
};
</script>

<template>
  <div class="app-container">
    <div class="header">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="default"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" size="default" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" size="default" @click="resetQuery"> 重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              size="default"
              @click="openSelectUser"
              v-hasPermi="['system:role:add']"
            >
              添加用户
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="CircleClose"
              size="default"
              :disabled="multiple"
              @click="cancelAuthUserAll"
              v-hasPermi="['system:role:remove']"
            >
              批量取消授权
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" size="default" @click="handleClose">
              关闭
            </el-button>
          </el-col>
          <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
        </el-row>
      </div>
      <div class="table-inner">
        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
          :row-class-name="proxy.$tableRowClassName"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户名称" prop="username" :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" prop="nickName" :show-overflow-tooltip="true" />
          <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" />
          <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center" prop="status">
            <template v-slot="scope">
              <DictTag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          ></el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button
                size="default"
                type="text"
                icon="CircleClose"
                @click="cancelAuthUser(scope.row)"
                v-hasPermi="['system:role:remove']"
              >
                取消授权
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          style="margin-top: 40px"
          v-show="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :background="true"
          layout="prev, pager, next, jumper, ->,  sizes, total"
          :total="total"
          @current-change="getList"
          @size-change="getList"
        />
      </div>
    </div>
    <selectUser ref="select" :roleId="queryParams.roleId" @ok="handleQuery" />
  </div>
</template>

<script lang="ts">
export default {
  dicts: ["sys_normal_disable"]
};
</script>

<style scoped lang="scss">
.header {
  display: flex;
  padding: 16px 16px 0px 16px;
  margin-bottom: 16px;
  border-radius: 4px;
  background: white;
  box-shadow: 0 0 12px rgb(0 0 0 / 5%);
}

.footer {
  flex: 1;
  display: flex;
  padding: 16px;
  flex-direction: column;
  border-radius: 4px;
  overflow: hidden;
  background: white;
  box-shadow: 0 0 12px rgb(0 0 0 / 5%);
  position: relative;
  box-sizing: border-box;

  .util {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
    flex-shrink: 0;
  }

  .table-inner {
    flex: 1;
    position: relative;
  }

  .table {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }
}
</style>
